import OSS from 'ali-oss'
import dt from '@dt/dt'
import fs from 'fs'
import moment from 'moment'

function config() {
  if (dt.env.env == 'dev' || dt.env.env == 'test') {
    return {
      endpoint: 'https://oss-cn-shanghai.aliyuncs.com',
      accessKeyId: 'LTAI5tDAUKf4xYJR6e1ZfeXy',
      accessKeySecret: 'AMgkrNS1Oy28ckZp8sezVXyrg06EBA',
      bucket: 'dtsh-image-dev',
      urlPrefix: 'https://dev-images.tospurfang.com/',
      secure: true,
      timeout: 600000
    }
  } else {
    return {
      endpoint: 'https://oss-cn-shanghai.aliyuncs.com',
      accessKeyId: 'LTAI5tNJjm7eKor7k27Mm6Fr',
      accessKeySecret: 'r09RqshwbvaILFYNNXjc9knhGuuZoo',
      bucket: 'dtsh-image',
      urlPrefix: 'https://images.tospurfang.com/',
      secure: true,
      timeout: 600000
    }
  }
}

function create() {
  return new OSS(config())
}

function name() {
  return moment().format('YYYYMMDD_HHmmss_') + Math.round(Math.random() * 100000)
}

function uploadVideo(file, progress) {
  let path = 'videos/' + name() + '.mp4'
  return create()
    .multipartUpload(path, file, {
      progress
    })
    .then((res) => {
      if (res.res.status == 200) {
        let url = config().urlPrefix + path
        return { url, name: path }
      } else {
        throw new Error('上传失败')
      }
    })
}

function cancel() {
  return create()
    .listUploads()
    .then((res) => {
      let ps = []
      res.uploads.forEach((up) => {
        ps.push(create().abortMultipartUpload(up.name, up.uploadId))
      })
      return Promise.all(ps)
    })
}

export default {
  uploadVideo,
  cancel
}
